package com.mall.shopping.services;

import com.mall.shopping.ICartService;

import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.CartItemConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import com.mall.shopping.utils.ExceptionProcessorUtils;


import com.mall.shopping.constant.GlobalConstants;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dto.*;
import com.mall.shopping.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;


import lombok.extern.slf4j.Slf4j;

import org.apache.dubbo.config.annotation.Service;
import org.redisson.Redisson;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;


import java.util.*;

import java.util.Map.Entry;


import static com.mall.shopping.constant.GlobalConstants.CART_ITEM_CACHE_PREFIX;

/**
 * @program: last-mall
 * @description:
 * @create: 2021-06-18 09:10
 **/


@Slf4j
@Service
public class ICartServiceImpl implements ICartService {

    @Autowired
    ItemMapper itemMapper;

//	@Override
//	public CartListByIdResponse getCartListById(CartListByIdRequest request) {
//		return null;
//	}

//	@Override
//	public AddCartResponse addToCart(AddCartRequest request) {
//		AddCartResponse response = new AddCartResponse();
//
//
//		try {
//			request.requestCheck();
//			Long itemId = request.getItemId();
//			Integer num = request.getNum();
//			Long userId = request.getUserId();
//
//			RedissonClient redissonClient = Redisson.create();
//			RMap<String, Object> cart = redissonClient.getMap("cart:"+userId);
//			Item item = itemMapper.selectByPrimaryKey(itemId);
//
//			CartProductDto cartProductDto = CartItemConverter.item2Dto(item);
//
//			cartProductDto.setChecked("true");
//			cartProductDto.setProductNum(Long.valueOf(num));
//
//			cart.put(CART_ITEM_CACHE_PREFIX + ":" + itemId,cartProductDto);
//			response.setCode(ShoppingRetCode.SUCCESS.getCode());
//			response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
//		} catch (Exception e) {
//			e.printStackTrace();
//			ExceptionProcessorUtils.wrapperHandlerException(response,e);
//		}
//
//		return response;
//	}
//
//	@Override
//	public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
//		return null;
//	}

//	@Override
//	public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
//		return null;
//	}

    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        DeleteCartItemResponse deleteCartItemResponse = new DeleteCartItemResponse();

        try {
            request.requestCheck();
            RedissonClient redissonClient = Redisson.create();
            RMap<String, Object> cart = redissonClient.getMap("cart:" + request.getUserId());
            String itemId = CART_ITEM_CACHE_PREFIX+ ":" + request.getItemId();
            Iterator<Entry<String, Object>> iterator = cart.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, Object> next = iterator.next();
                if (itemId.equals(next.getKey())) {
                    iterator.remove();
                }
            }

            deleteCartItemResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            deleteCartItemResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            log.error("ICartServiceImpl.deleteCartItem occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(deleteCartItemResponse, e);
        }

        return deleteCartItemResponse;
    }


    //删除购物⻋中选中的商品
    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        DeleteCheckedItemResposne resposne = new DeleteCheckedItemResposne();

        try {
            //参数检验
            request.requestCheck();

            Long userId = request.getUserId();

            RedissonClient redissonClient = Redisson.create();
            RMap<String, Object> cart = redissonClient.getMap("cart:" + userId);

            //循环遍历该用户购物车中的商品,删除选中的商品
            Iterator<Map.Entry<String, Object>> iterator = cart.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> next = iterator.next();
                CartProductDto value = (CartProductDto) next.getValue();
                if ("true".equals(value.getChecked())) {
                    iterator.remove();
                }
            }

            resposne.setCode(ShoppingRetCode.SUCCESS.getCode());
            resposne.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(resposne, e);
        }

        return resposne;
    }

//	@Override
//	public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
//		return null;
//	}

    @Autowired
    RedissonClient redissonClient;

    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        CartListByIdResponse response = new CartListByIdResponse();
        try {

            request.requestCheck();

            Long userId = request.getUserId();

            RMap<Object, Object> map = redissonClient.getMap("cart:" + userId);
            ArrayList<CartProductDto> cartProductDtos = new ArrayList<>();
            Collection<Object> values = map.values();
            for (Object value : values) {
                cartProductDtos.add((CartProductDto) value);
            }
            response.setCartProductDtos(cartProductDtos);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

            return response;
        } catch (Exception e) {
            log.error("ICartServiceImpl.getCartListById occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse response = new AddCartResponse();

        try {
            request.requestCheck();
            Long itemId = request.getItemId();
            Integer num = request.getNum();
            Long userId = request.getUserId();

            RedissonClient redissonClient = Redisson.create();
            RMap<String, CartProductDto> cart = redissonClient.getMap("cart:" + userId);
            Item item = itemMapper.selectByPrimaryKey(itemId);

            CartProductDto cartProductDto = CartItemConverter.item2Dto(item);

            cartProductDto.setChecked("true");
            cartProductDto.setProductNum(Long.valueOf(num));

            CartProductDto productDto = cart.get(CART_ITEM_CACHE_PREFIX + ":" + itemId);
            if (!ObjectUtils.isEmpty(productDto)){
                Long productNum = productDto.getProductNum();
                cartProductDto.setProductNum(Long.valueOf(num)+productNum);
            }

            cart.put(CART_ITEM_CACHE_PREFIX + ":" + itemId, cartProductDto);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }

    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        UpdateCartNumResponse response = new UpdateCartNumResponse();
        request.requestCheck();
        try {
            String checked = request.getChecked();
            Long userId = request.getUserId();
            Long itemId = request.getItemId();
            RMap<String, CartProductDto> map = redissonClient.getMap("cart:" + userId);

            CartProductDto cartProductDto = map.get(GlobalConstants.CART_ITEM_CACHE_PREFIX + ":" + itemId);
            cartProductDto.setProductNum(request.getNum().longValue());
            cartProductDto.setChecked(checked);
            map.put(GlobalConstants.CART_ITEM_CACHE_PREFIX + ":" + itemId, cartProductDto);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            return response;

        } catch (Exception e) {
            log.error("ICartServiceImpl.getCartListById occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }

    /**
     * 检查所有车项目
     *
     * @param request 请求
     * @return {@link CheckAllItemResponse}
     */
    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        CheckAllItemResponse response = new CheckAllItemResponse();
        try {
            request.requestCheck();

            Long userId = request.getUserId();
            String checked = request.getChecked();
            RMap<String, CartProductDto> map = redissonClient.getMap("cart:" + userId);

            for (Entry<String, CartProductDto> entry : map.entrySet()) {
                CartProductDto value = entry.getValue();
                value.setChecked(checked);
            }

            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            return response;
        } catch (Exception e) {
            log.error("ICartServiceImpl.checkAllCartItem occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }

//    @Override
//    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
//        return null;
//    }

//    @Override
//    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
//        return null;
//    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        return null;
    }

}

